import { Controller, Get, Param } from '@nestjs/common';
import { ChargeStrategy } from 'src/entities/ChargeStrategy';
import { DevicePortRecord, DeviceRecord } from 'src/types';
import { errorReturn, isNumber, successReturn } from 'src/utils';
import { ChargeStrategyService } from '../charge-strategy/charge-strategy.service';
import { DevicePortService } from '../device-port/device-port.service';
import { MerchantService } from '../merchant/merchant.service';
import { DeviceService } from './device.service';

@Controller('device')
export class DeviceController {
    constructor(
        private deviceService:DeviceService,
        private devicePortService:DevicePortService,
        private merchantService:MerchantService,
        private chargeStrategyService:ChargeStrategyService
    ) {}
    @Get(':deviceId')
    async device(@Param('deviceId') deviceId:number) {
        deviceId = Number(deviceId)
        if(!isNumber(deviceId) || deviceId < 1) return null

        const data:{
            device?:DeviceRecord,
            portList? : {[key in keyof DevicePortRecord]? : DevicePortRecord[key]}[],
            strategy?:ChargeStrategy,
            serviceTel?:string
        } = {
            
        }

        let device = await this.deviceService.device(deviceId, ['merchantId', 'strategyId'])
        if(!device) return null
        
        data.device = device

        data.portList = await this.devicePortService.portList(deviceId, ['portNo', 'status'])

        if(device.merchantId > 0) {
            const merchant = await this.merchantService.merchant(device.merchantId, ['phone'])
            if(merchant) {
                data.serviceTel = merchant.phone
            }
        }

        if(device.strategyId > 0) {
            data.strategy = await this.chargeStrategyService.strategy(device.strategyId, ['options', 'unitPrice', 'rules', 'strategyType', 'remark'])
        }

        return successReturn(data)
    }

    @Get('strategy/:deviceId')
    async strategry(@Param('deviceId') deviceId:number) {
        deviceId = Number(deviceId)
        if(!isNumber(deviceId) || deviceId <= 0) return errorReturn()
        const device = await this.deviceService.device(deviceId, ['strategyId'])
        const strategy = await this.chargeStrategyService.strategy(device.strategyId, ['options', 'unitPrice', 'rules', 'strategyType', 'remark'])
        return successReturn(strategy)
    }
}
